package main

import (
	"bufio"
	"encoding/csv"
	"flag"
	"fmt"
	"os"
	"regexp"
	"strings"
)

type LogEntry struct {
	Timestamp    string
	Interface    string
	RequestTime  string
	DeviceID     string
	FromApp      string
	Server       string
	OtherContent string
}

func main() {
	filePath := flag.String("file", "", "Path to the file to be analyzed")
	flag.Parse()
	// 打开日志文件
	logFile, err := os.Open(*filePath)
	if err != nil {
		fmt.Println("Error opening log file:", err)
		return
	}
	defer logFile.Close()

	// 创建CSV文件
	csvFile, err := os.Create("output.csv")
	if err != nil {
		fmt.Println("Error creating CSV file:", err)
		return
	}
	defer csvFile.Close()

	writer := csv.NewWriter(csvFile)
	defer writer.Flush()

	// 写入CSV文件的表头
	headers := []string{"Timestamp", "Interface", "RequestTime", "DeviceID", "FromApp", "Server", "OtherContent"}
	writer.Write(headers)

	// 定义日志解析正则表达式
	re := regexp.MustCompile(`(\d+\.\d+\.\d+\.\d+ - - \[(.*?)\] "(.*?)" request_time:"(.*?)" device_id: "(.*?)" from_app: "(.*?)" upstream_server: "(.*?)" (\d+) (\d+) "(.*?)" "(.*?)" "(.*?)" "(.*?)")`)

	scanner := bufio.NewScanner(logFile)
	for scanner.Scan() {
		line := scanner.Text()
		matches := re.FindStringSubmatch(line)
		if len(matches) > 0 {
			entry := LogEntry{
				Timestamp:    matches[2],
				Interface:    matches[3],
				RequestTime:  matches[4],
				DeviceID:     matches[5],
				FromApp:      matches[6],
				Server:       matches[7],
				OtherContent: strings.Join(matches[8:], " "),
			}
			writer.Write([]string{entry.Timestamp, entry.Interface, entry.RequestTime, entry.DeviceID, entry.FromApp, entry.Server, entry.OtherContent})
		}
	}

	if err := scanner.Err(); err != nil {
		fmt.Println("Error reading log file:", err)
	}
}
